package com.zsj.Tree;

/**
 * @Author zsj
 * @Version 1.0
 * @Date 2024/4/13 13:05
 * @Description 二叉树的前中后序遍历
 */
public class TreeTraversalByRecursion {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1
                , new TreeNode(2, new TreeNode(4), null),
                new TreeNode(3, new TreeNode(5), new TreeNode(6)));
//        preOrder(treeNode);

//        inorder(treeNode);
        postOrder(treeNode);
    }

    /**
     * 前序遍历
     * 先当前节点 然后左节点 然后右节点
     */
    public static void preOrder(TreeNode node) {
        if (node == null) return;
        System.out.print(node.val + "\t");
        if (node.left != null) preOrder(node.left);
        if (node.right != null) preOrder(node.right);
    }

    /**
     * 中序遍历
     * 先左节点 然后当前节点 最后右节点
     */
    public static void inorder(TreeNode node) {
        if (node == null) return;
        inorder(node.left);
        System.out.println(node.val);
        inorder(node.right);
    }

    /**
     * 后续遍历
     * 先左 然后右 最后当前节点
     */
    public static void postOrder(TreeNode node) {
        if (node == null) return;
        postOrder(node.left);
        postOrder(node.right);
        System.out.print(node.val + "\t");
    }
}
